import { createRouter, createWebHistory } from 'vue-router'
import { isLoggedIn } from '@/utils/auth'

const routes = [{
        path: '/login',
        name: 'Login',
        component: () =>
            import ('../views/Login.vue')
    },
    {
        path: '/',
        name: 'Layout',
        component: () =>
            import ('../layout/index.vue'),
        redirect: '/home',
        children: [{
                path: 'home',
                name: 'Home',
                component: () =>
                    import ('../views/Home.vue')
            },
            {
                path: 'profile',
                name: 'Profile',
                component: () =>
                    import ('../views/Profile.vue')
            },
            {
                path: 'region/:id',
                name: 'RegionSafety',
                component: () =>
                    import ('../views/RegionSafety.vue')
            },
            {
                path: 'work-record',
                name: 'WorkRecord',
                component: () =>
                    import ('../views/WorkRecord.vue')
            },
            {
                path: 'account-info',
                name: 'AccountInfo',
                component: () =>
                    import ('../views/AccountInfo.vue')
            },
            {
                path: 'leave',
                name: 'LeaveForm',
                component: () =>
                    import ('../views/LeaveForm.vue')
            },
            {
                path: 'my-leaves',
                name: 'LeaveList',
                component: () =>
                    import ('../views/LeaveList.vue')
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫 - 检查登录状态
router.beforeEach((to, from, next) => {
    // 如果访问登录页
    if (to.path === '/login') {
        // 如果已经登录，重定向到首页
        if (isLoggedIn()) {
            next('/home')
        } else {
            next()
        }
    } else {
        // 如果访问其他页面
        if (isLoggedIn()) {
            // 已登录，允许访问
            next()
        } else {
            // 未登录，重定向到登录页
            next('/login')
        }
    }
})

export default router